// UI管理器
class UIManager {
    constructor() {
        this.currentScreen = 'login';
        this.init();
    }

    init() {
        this.setupLoginScreen();
        this.setupRoomScreen();
        this.setupGameUI();
    }

    setupLoginScreen() {
        const guestBtn = document.getElementById('guest-login');
        const registerBtn = document.getElementById('register-login');
        const usernameInput = document.getElementById('username');

        guestBtn.addEventListener('click', () => {
            const username = usernameInput.value.trim() || '游客' + Math.floor(Math.random() * 1000);
            this.login(username);
        });

        registerBtn.addEventListener('click', () => {
            const username = usernameInput.value.trim();
            if (username) {
                this.login(username);
            } else {
                alert('请输入用户名');
            }
        });
    }

    setupRoomScreen() {
        const quickJoinBtn = document.getElementById('quick-join');
        const createRoomBtn = document.getElementById('create-room');
        const roomCodeInput = document.getElementById('room-code');

        quickJoinBtn.addEventListener('click', () => {
            this.joinRandomRoom();
        });

        createRoomBtn.addEventListener('click', () => {
            this.createRoom();
        });

        roomCodeInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                this.joinRoomByCode(roomCodeInput.value.trim());
            }
        });
    }

    setupGameUI() {
        window.updateInventory = (inventory) => {
            this.updateInventoryDisplay(inventory);
        };
    }

    login(username) {
        localStorage.setItem('username', username);
        this.showScreen('room');
        this.loadRoomList();
    }

    showScreen(screenName) {
        document.querySelectorAll('.screen').forEach(screen => {
            screen.classList.remove('active');
        });
        document.getElementById(`${screenName}-screen`).classList.add('active');
        this.currentScreen = screenName;
    }

    loadRoomList() {
        // 模拟房间列表
        const roomList = document.getElementById('room-list');
        roomList.innerHTML = '';
        
        const mockRooms = [
            { id: 'ABC123', players: 3, maxPlayers: 8 },
            { id: 'DEF456', players: 5, maxPlayers: 8 },
            { id: 'GHI789', players: 1, maxPlayers: 8 }
        ];

        mockRooms.forEach(room => {
            const roomItem = document.createElement('div');
            roomItem.className = 'room-item';
            roomItem.innerHTML = `
                <span>房间 ${room.id}</span>
                <span>${room.players}/${room.maxPlayers} 人</span>
            `;
            roomItem.addEventListener('click', () => {
                this.joinRoomByCode(room.id);
            });
            roomList.appendChild(roomItem);
        });
    }

    createRoom() {
        const roomCode = this.generateRoomCode();
        this.joinRoom(roomCode, true);
    }

    joinRandomRoom() {
        const mockRooms = ['ABC123', 'DEF456', 'GHI789'];
        const randomRoom = mockRooms[Math.floor(Math.random() * mockRooms.length)];
        this.joinRoom(randomRoom);
    }

    joinRoomByCode(code) {
        if (code.length === 6) {
            this.joinRoom(code);
        } else {
            alert('房间码必须是6位字符');
        }
    }

    joinRoom(roomCode, isHost = false) {
        document.getElementById('room-code-display').textContent = `房间: ${roomCode}`;
        this.showScreen('game');
        
        // 初始化游戏
        if (typeof initGame === 'function') {
            initGame();
        }
        
        // 初始化网络连接
        if (typeof NetworkManager === 'function') {
            window.network = new NetworkManager(roomCode, isHost);
        }
    }

    generateRoomCode() {
        const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        let code = '';
        for (let i = 0; i < 6; i++) {
            code += chars.charAt(Math.floor(Math.random() * chars.length));
        }
        return code;
    }

    updateInventoryDisplay(inventory) {
        const grid = document.getElementById('inventory-grid');
        if (!grid) return;

        grid.innerHTML = '';
        
        const items = [
            { name: 'wood', display: '木', color: '#8B4513' },
            { name: 'stone', display: '石', color: '#808080' },
            { name: 'coal', display: '煤', color: '#000000' },
            { name: 'iron', display: '铁', color: '#C0C0C0' },
            { name: 'gold', display: '金', color: '#FFD700' }
        ];

        items.forEach((item, index) => {
            const slot = document.createElement('div');
            slot.className = 'inventory-slot';
            slot.style.backgroundColor = item.color;
            slot.style.color = item.color === '#000000' ? '#FFFFFF' : '#000000';
            slot.textContent = `${item.display}:${inventory[item.name] || 0}`;
            slot.title = item.name;
            
            slot.addEventListener('click', () => {
                // 选择该物品
                console.log(`Selected ${item.name}`);
            });
            
            grid.appendChild(slot);
        });

        // 添加合成配方
        this.updateCraftingRecipes(inventory);
    }

    updateCraftingRecipes(inventory) {
        const recipes = document.getElementById('crafting-recipes');
        if (!recipes) return;

        recipes.innerHTML = '';

        const craftableItems = [
            { name: '木剑', requires: { wood: 2 }, gives: 'weapon' },
            { name: '火把', requires: { wood: 1, coal: 1 }, gives: 'torch' },
            { name: '石斧', requires: { wood: 2, stone: 3 }, gives: 'axe' }
        ];

        craftableItems.forEach(recipe => {
            const canCraft = Object.entries(recipe.requires).every(([item, count]) => 
                (inventory[item] || 0) >= count
            );

            const recipeDiv = document.createElement('div');
            recipeDiv.className = 'crafting-recipe';
            recipeDiv.textContent = recipe.name;
            recipeDiv.style.opacity = canCraft ? '1' : '0.5';
            
            if (canCraft) {
                recipeDiv.addEventListener('click', () => {
                    this.craftItem(recipe);
                });
            }
            
            recipes.appendChild(recipeDiv);
        });
    }

    craftItem(recipe) {
        // 实现合成逻辑
        console.log('Crafting:', recipe.name);
        
        // 扣除材料
        Object.entries(recipe.requires).forEach(([item, count]) => {
            if (window.game && window.game.scene.scenes[0]) {
                window.game.scene.scenes[0].inventory[item] -= count;
            }
        });
        
        // 更新UI
        if (window.game && window.game.scene.scenes[0]) {
            window.game.scene.scenes[0].updateUI();
        }
    }
}

// 初始化UI管理器
let uiManager;
document.addEventListener('DOMContentLoaded', () => {
    uiManager = new UIManager();
});